package com.servlet.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.servlet.bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Title: UserServlet
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2023/12/22 13:44
 */
@WebServlet("/users02")
public class UserServlet02 extends HttpServlet {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 接受回调函数
        String callback = req.getParameter("callback");


        req.setCharacterEncoding("utf-8");
        // 创建用户
        List<User> users = Arrays.asList(
                new User("小明","123456",new Date()),
                new User("小红","123456",new Date()),
                new User("寒梅","123456",new Date())
        );
        String s = objectMapper.writeValueAsString(users);
        resp.setHeader("Content-Type","application/json;charset=utf-8");
        resp.getWriter().write(callback+"("+s+")");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}
